package com.ml.ws.client;


import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.log4j.Logger;

public class WSClient {

	private static Logger logger = Logger.getLogger(WSClient.class);
	
	private static String PROJECT_URL = "http://localhost:8080/webservice/ws/query/test/";
	
	public static void main(String[] args) {
		
		String param = "asas啊实打实大是";
		
		try {
			WSClient.doPost(PROJECT_URL+URLEncoder.encode(param, "UTF-8")+".json", null);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			WSClient.doPost(PROJECT_URL+URLEncoder.encode(param, "UTF-8"), null);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static String doPost(String restUrl, String data){
		String resp = null;
		try {
			HttpClient client = new HttpClient();
			// 创建POST方法的实例
			PostMethod method = new PostMethod(restUrl);
			
			method.getParams().setContentCharset("UTF-8");  
			method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
			
			// 设置请求数据
//			method.setRequestEntity(new StringRequestEntity(data, "text/plain",
//					"UTF-8"));
			
			
			//NameValuePair nvp = new NameValuePair("data", data);
			//method.setQueryString(new NameValuePair[]{nvp});
			
			
			// method.setRequestEntity(new StringRequestEntity(data, "text/plain",
			// Tag.CHARSET_ISO88591));
			// 缺省支持UTF-8
			
//			client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,
//					"UTF-8");
			
			
			int status = client.executeMethod(method);
			if (status == HttpStatus.SC_OK) {
				
				InputStream in = method.getResponseBodyAsStream();
				
				BufferedReader reader = new BufferedReader(new InputStreamReader(in), 16*1024);
				
				StringBuffer sb = new StringBuffer("\n");
				
				while((resp=reader.readLine()) != null){
					sb.append(resp+"\n");
				}
				
//				resp = method.getResponseBodyAsString();
//				logger.info("url=" + restUrl + "返回：" + resp);
				logger.info("url=" + restUrl + "返回：" + sb.toString());
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			
		}
		return resp;
	}
	
	
}
